﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Data;
using StoragePeriod.Common;
using System.Collections;
using StoragePeriod.Web.Common;
using System.Text;

namespace StoragePeriod.Web.SysManage
{
    public partial class PrivRoleManager : SecurityPage
    {
        public Role CurrentRole
        {
            get
            {
                return Role.Where("RoleCode == @0", RoleCode).FirstOrDefault();
            }
        }

        public List<string> CurrentRolePrivilege
        {
            get
            {
                return RolePrivileges.Where("RoleCode==@0", RoleCode).Select(p => p.PrivCode).ToList();
            }
        }

        public string RoleCode
        {
            get
            {
                return hfRoleCode.Value.EToString();
            }
            set
            {
                hfRoleCode.Value = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            repRoleList.DataSource = LinqUtility.LinqContext.Role.Select(p => new { Name = p.RoleName, Value = p.RoleCode });
            repRoleList.DataBind();
            BindCurretlyRolePrivliege();
        }

        public void roleAct_Click(object sender, EventArgs e)
        {
            LinkButton linkB = sender as LinkButton;
            RoleCode = linkB.CommandArgument;
            linkB.CssClass += " sp-list-item-seleted";
            BindCurretlyRolePrivliege();
        }

        private void BindCurretlyRolePrivliege()
        {
            //添加角色按钮在选择了角色时禁用
            //btAddRole.Enabled = RoleCode.IsNullOrEmpty();

            if (RoleCode.IsNullOrEmpty())
            {
                var defaultRole = Role.All().FirstOrDefault();
                if (defaultRole != null)
                    RoleCode = defaultRole.RoleCode;
            }

            var res = Privileges.Where("PrivType==@0", PrivType.Category.EToString()).Select(p => new
            {
                CategoryName = p.PrivName,
                SubPages = LoadSubPagesFromPrivCode(p.PrivCode)
            });

            repPrivModule.DataSource = res;
            repPrivModule.DataBind();

            if (CurrentRole == null) return;
            txt_roleName.Text = CurrentRole.RoleName;
            txt_roledesc.Text = CurrentRole.RoleLongName;

            Page.Controls.AllOfType<LinkButton>().ToList().ForEach(p =>
            {
                if (p.CommandArgument == RoleCode)
                {
                    p.CssClass += " sp-list-item-seleted";
                }
            });
        }
        /// <summary>
        ///绑定页面
        /// </summary>
        private object LoadSubPagesFromPrivCode(string pc)
        {
            return Privileges.Where("ParentPrivCode==@0", pc).Select(p => new
            {
                PageName = p.PrivName,
                Value = p.PrivCode,
                PrivType = p.PrivType,
                SubPrivs = LoadSubPrivsFromPage(p.PrivCode)
            });
        }
        /// <summary>
        ///绑定权限
        /// </summary> 
        private object LoadSubPrivsFromPage(string pc)
        {
            return Privileges.Where("ParentPrivCode==@0", pc).Select(p => new
            {
                Text = p.PrivName,
                Value = p.PrivCode + "-" + p.PrivType
            });
        }

        /// <summary>
        /// 绑定分类
        /// </summary> 
        protected void repPrivModule_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Repeater rep = sender as Repeater;
            Repeater subpages = e.Item.FindControl("subPageList") as Repeater;
            subpages.DataSource = e.Item.DataItem.TryGetValue("SubPages");
            subpages.DataBind();
        }
        /// <summary>
        /// 绑定页面
        /// </summary> 
        protected void subPageList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Repeater rep = sender as Repeater;
            CheckBoxList SubPrivs = e.Item.FindControl("subPrivs") as CheckBoxList;
            CheckBox pagePriv = e.Item.FindControl("PageViewPrivilege") as CheckBox;
            pagePriv.Checked = CurrentRolePrivilege.Contains(e.Item.DataItem.TryGetValue("Value").EToString());

            SubPrivs.DataSource = e.Item.DataItem.TryGetValue("SubPrivs");
            SubPrivs.DataTextField = "Text";
            SubPrivs.DataValueField = "Value";

            SubPrivs.DataBind();
        }

        protected void subPrivs_ItemDataBound(object sender, EventArgs e)
        {
            CheckBoxList privLists = sender as CheckBoxList;
            foreach (ListItem item in privLists.Items)
            {
                var values = item.Value.Split('-');
                item.Attributes["PrivType"] = values[1];
                item.Value = values[0];
                item.Selected = CurrentRolePrivilege.Contains(item.Value);
            }
        }

        protected void btAddRole_Click(object sender, EventArgs e)
        {
            Role newRole = new Role()
            {
                RoleID = Guid.NewGuid().EToString(),
                RoleCode = Utility.NewPrivCode(),
                RoleName = txt_roleName.Text,
                RoleLongName = txt_roledesc.Text
            };
            Role.Insert(newRole);
            Page.Alert("操作成功");
            BindData();
        }

        protected void btDeleteRole_Click(object sender, EventArgs e)
        {
            Role.Delete("RoleCode=@0", RoleCode);
            Page.Alert("操作成功");

            RoleCode = string.Empty;
            BindData();
        }

        protected void btModfiyRole_Click(object sender, EventArgs e)
        {
            CurrentRole.RoleName = txt_roleName.Text;
            CurrentRole.RoleLongName = txt_roledesc.Text;

            LinqUtility.LinqContext.SubmitChanges();
            Page.Alert("操作成功");
            BindData();
        }

        /// <summary>
        /// 保存权限
        /// </summary> 
        protected void btSavePrivilege_Click(object sender, EventArgs e)
        {
            if (CurrentRole == null)
            {
                Page.Alert("请先选择一个角色再进行操作");
                return;
            }

            var deletePrivs = RolePrivileges.Where("RoleCode==@0", RoleCode);

            LinqUtility.LinqContext.RolePrivileges.DeleteAllOnSubmit(deletePrivs);
            LinqUtility.LinqContext.SubmitChanges();

            var res = new List<RolePrivileges>();

            res.AddRange(repPrivModule.Controls.AllOfType<CheckBox>().Where(p => p.Checked)
                .ToList().Select(p => new RolePrivileges()
                {
                    PrivCode = p.Attributes["PrivCode"],
                    RoleCode = CurrentRole.RoleCode,
                    PrivType = p.Attributes["PrivType"]
                }).ToList());

            repPrivModule.Controls.AllOfType<CheckBoxList>().ToList().ForEach(p =>
            {
                foreach (ListItem item in p.Items)
                {
                    if (item.Selected)
                        res.Add(new RolePrivileges()
                        {
                            PrivCode = item.Value,
                            RoleCode = CurrentRole.RoleCode,
                            PrivType = item.Attributes["PrivType"]
                        });
                }
            });

            LinqUtility.LinqContext.RolePrivileges.InsertAllOnSubmit(res);
            LinqUtility.LinqContext.SubmitChanges();

            Page.Alert("操作成功");
            BindData();
        }
    }
}